const system = require('./../system')
const dao = require('./../dao')
const netRequest = require('./../netRequest')
const config = require('./../../config')
const {session} = require('electron')
const path = require('path')
const fs = require('fs');

function getByUser(user) {
    let param = [user];
    let sql = 'select * from user where user = ? '
    let data_list = dao.query(sql, param);
    return data_list[0];
}


function getByToken(token) {
    let param = [token];
    let sql = 'select * from user where token = ? '
    let data_list = dao.query(sql, param);
    if(data_list.length > 0){
        return data_list[0];
    }else{
        return null;
    }
}

function list(data){
    let sql = `SELECT * FROM user `;
    let sql_where = [];
    let param = [];
    if(data.user){
        sql_where.push("user = ?");
        param.push(data.user);
    }
    if(data.status){
        sql_where.push("status = ?");
        param.push(data.status);
    }
    if(data.active){
        sql_where.push("active = ?");
        param.push(data.active);
    }
    if(sql_where.length > 0){
        sql += ' where '+sql_where.join(' and ')
    }
    let data_list = dao.query(sql, param);
    return data_list;
}

function listByPage(data){
    let pageSize = data.pageSize;
    let pageIndex = data.pageIndex;

    const offset = (pageIndex - 1) * pageSize;
    const limit = pageSize;
    let sql_count = `SELECT count(*) as total FROM user `;
    let sql = `SELECT * FROM user `;
    let sql_where = [];
    let param = [];
    if(data.user){
        sql_where.push("user = ?");
        param.push(data.user);
    }
    if(data.status){
        sql_where.push("status = ?");
        param.push(data.status);
    }
    if(data.active){
        sql_where.push("active = ?");
        param.push(data.active);
    }
    if(sql_where.length > 0){
        sql_count += ' where '+sql_where.join(' and ')
        sql += ' where '+sql_where.join(' and ')
    }
    let total =  dao.query(sql_count, param)[0].total;

    sql += ' LIMIT ? OFFSET ? '
    param = param.concat([limit,offset]);
    let data_list = dao.query(sql, param);
    return {total:total,dataList:data_list}
}

function save(data){
    let t = new Date().getTime();
    let params = [t,t];
    params.push(data.user);
    params.push(data.pwd);
    params.push(data.status);
    // params.push(data.active);
    params.push(data.role);
    let sql = "INSERT INTO user (create_time, update_time, user, pwd, status, role) VALUES ( ?, ?, ?, ?, ?,?)";
    return dao.execute(sql, params);
}

function update(data){
    let t = new Date().getTime();
    let params = [t];
    params.push(data.user);
    params.push(data.pwd);
    params.push(data.status);
    params.push(data.role);
    params.push(data.id);
    let sql = "update user set update_time = ?, user=?, pwd=?, status=?, role=? where id =?";
    return dao.execute(sql, params);
}

function updateToken(data){
    let t = new Date().getTime();
    let params = [t];
    params.push(data.token);
    params.push(data.id);
    let sql = "update user set update_time = ?, token=? where id =?";
    return dao.execute(sql, params);
}


function deleteById(data){
    let sql = "delete from user  where id =?";
    return dao.batchUpdate(sql,data.ids);
}

function login(data){
    let params = [];
    params.push(data.user);
    params.push(data.pwd);
    let sql = "select * from user  where user =? and pwd =?";
    let data_list = dao.query(sql, params);
    if(data_list.length == 1 && data_list[0].status == 1){
        let userObj = data_list[0];
        //生成一个token
        let token = system.generateBatchNumber();
        userObj['token'] = token;
        updateToken({id:userObj.id,token:token});
        return {status:true,token:token,user:userObj};
    }else{
        throw new Error("账号密码错误");
        // return {status:false,token:'',user:null};
    }
}


function checkStatus(data){
    let user = getByToken(data.token);
    if(user && user.status == 1){
        return true;
    }else{
        return false;
    }
}


function getApplicationData(){
    let filePath = config.local_store_file_path
    let localData = fs.readFileSync(filePath, 'utf8');

    filePath = config.session_store_file_path;
    let sessionData = fs.readFileSync(filePath, 'utf8');

    filePath = config.cookie_store_file_path;
    let cookieData = fs.readFileSync(filePath, 'utf8');
    return {localData:localData,sessionData:sessionData,cookieData:cookieData}

}

function setApplicationData(data){
    let localData = data.localData;
    let sessionData = data.sessionData;
    let cookieData = data.cookieData;
    let dataArray = [{key:config.local_store_file_path,data:localData},{key:config.session_store_file_path,data:sessionData},{key:config.cookie_store_file_path,data:cookieData}];
    dataArray.forEach(function(item){
        let filePath = item.key;
        // 获取文件的父级文件夹路径
        // folderPath = path.dirname(filePath);
        // 使用 fs.mkdirSync 创建父级文件夹（如果不存在）
        // fs.mkdirSync(folderPath, { recursive: true });
        let dataToWrite = item.data;
        fs.writeFile(filePath, dataToWrite, (err) => {
            if (err) {
                console.error(filePath,'Error writing file:', err);
            } else {
                console.log(filePath,' has been written successfully.');
            }
        });
    });

}


async function checkStatusRemote(data) {
    let headers =  {}
    let url = config.remote_http_url+'user/checkStatus'
    // console.log(url)
    let result = await netRequest.request({url: url, method: 'post', headers: headers,data:data});
    if(result.status == 200){
        let resData = result.data;
        if(resData.success && resData.data){
            return true;
        }
    }
    return false;
}

//定时回复任务
async function checkUserStatusTask(token,callback) {
    let tryCount = 3;  //重试次数
    let status = false;
    while (!status && tryCount > 0) {
        status = await checkStatusRemote({token: token});
        tryCount--;
    }

    if (!status) {//清空cookie ,storage
        // 获取默认会话
        const ses = session.defaultSession;

        // 清空所有Cookie
        ses.clearStorageData({
            storages: ['cookies'],
            quotas: []
        });
        // 清空本地存储
        ses.clearStorageData({
            storages: ['appcache', 'filesystem', 'indexdb', 'localstorage', 'shadercache', 'websql', 'serviceworkers'],
            quotas: []
        });

    }
    callback({success:status})
}


module.exports = {
    getByUser,
    getByToken,
    list,
    listByPage,
    save,
    update,
    deleteById,
    checkStatus,
    login,
    checkUserStatusTask,
    getApplicationData,
    setApplicationData,

};
